package com.czk.config;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/23 13:52
 */
public class NettyClient {
    private NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture connect(String host, Integer port) {
        ChannelFuture channelFuture = null;
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(bossGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new MyClientChannelInitializer());
            channelFuture = bootstrap.connect(host, port).syncUninterruptibly();
            this.channel = channelFuture.channel();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                System.out.println("连接成功");
            } else {
                System.out.println("连接失败");
            }
        }
        return channelFuture;
    }

    public void destroy() {
        if (null == channel) return;
        channel.close();
        bossGroup.shutdownGracefully();
    }
}
